<template>
    <div class="report">
        <Modal v-model="submitModal.show" title="提交报告" footer-hide>
            <div class="alert-wrapper">
                <Alert type="warning" show-icon>
                    <p v-if="!isTargetAdmin">1、为了方便裁判审核报告，请使用漏洞名命名报告</p>
                    <p v-else>1、为了方便裁判审核报告，请使用目标名+被攻击漏洞名命名报告</p>
                    <p>2、只支持上传pdf和word类型文档</p>
                    <p>3、文件名不能包含下列任意英文字符 \ / : * ? " &lt > |，名字长度不超过50</p>
                    <!-- 文件名只能包含数字，英文，汉字或下划线 -->
                    <p>4、文件大小不超过10M</p>
                </Alert>
            </div>
            <div style="display: flex; flex-direction: column">
                <Cascader
                    :data="cascaderData"
                    v-model="party"
                    placeholder="请选择提交人"
                    style="margin-bottom: 10px;width: 100%;"
                ></Cascader>
                <!-- 综合累加模式在团队任务里面提交不显示 -->
                <Select filterable
                    v-if="!zhSubmitTargetId" 
                    transfer
                    v-model="targetId"
                    :placeholder="`请选择${drillDetail.type === 7 ? '任务':'靶标'}`"
                    style="width: 100%; margin-bottom: 10px"
                    filterable
                    clearable
                >
                    <Option
                        :value="item.id"
                        v-for="item in targetList"
                        :key="item.id || item.targetId"
                        :title="item.name || item.targetName"
                        >{{ item.name || item.targetName }}</Option
                    >
                </Select>
                <Select filterable
                    transfer
                    v-model="attack"
                    placeholder="请选择攻击类型"
                    style="width: 100%; margin-bottom: 10px"
                    filterable
                    clearable
                >
                    <Option
                        :value="item.id"
                        v-for="item in attackList"
                        :key="item.id"
                        :title="item.category"
                        >{{ item.category }}</Option
                    >
                </Select>
                <div>
                    <Upload
                        ref="upload"
                        :action="uploadAction"
                        :show-upload-list="false"
                        :before-upload="beforeUpload"
                        :on-format-error="handleFormatError"
                        :on-exceeded-size="fileHasExceed"
                        :on-success="submitReport"
                        :headers="uploadHeader"
                        :on-progress="handleUploadProgress"
                        :disabled="
                            !attack || party.length !== 2 || !targetId || 
                            (drillDetail.type != 7 &&
                                !taskReportListDatas.some((item) => item.status === 'running')) ||
                            isSubmitting ||
                            (drillDetail.progress != '4' && drillDetail.progress != '2')
                        "
                        :format="['doc', 'pdf', 'docx']"
                    >
                        <Button
                            type="primary"
                            :disabled="
                                !attack || party.length !== 2 || !targetId ||
                                (drillDetail.type != 7 &&
                                    !taskReportListDatas.some(
                                        (item) => item.status === 'running'
                                    )) ||
                                isSubmitting ||
                                (drillDetail.progress != '4' && drillDetail.progress != '2')
                            "
                            icon="ios-cloud-upload-outline"
                            >提交报告</Button
                        >
                    </Upload>
                    <span
                        v-if="showTip"
                        style="
                            color: red;
                            line-height: 30px;
                            height: 30px;
                            display: inline-block;
                            margin-bottom: 8px;
                            margin-left: 6px;
                        "
                        >{{ showTipInfo }}</span
                    >
                </div>
            </div>
        </Modal>
        <Modal
            v-model="tipModal.show"
            title=""
            :mask-closable="false"
            :width="300"
            class="tipModel"
        >
            <div class="ivu-modal-confirm-head">
                <div
                    class="ivu-modal-confirm-head-icon"
                    :class="
                        tipModal.submitSuccess
                            ? 'ivu-modal-confirm-head-icon-success'
                            : 'ivu-modal-confirm-head-icon-warning'
                    "
                >
                    <i class="ivu-icon ivu-icon-ios-checkmark-circle"></i>
                </div>
                <div class="ivu-modal-confirm-head-title">{{ tipModal.content }}</div>
            </div>
        </Modal>
    </div>
</template>
<script>
import cookieUse from '@/libs/cookie.js';
import { submitFile, updateFile } from '@/api/drill.js';
import { getaccessgrouplist } from '@/api/access_new';
import {
    getPneAttackTarget,
    getPneDefenseTarget,
    getTargetTeamList_new,
    queryTargetAllot,
    designerSubmitReport,
    queryHWAttackTypes,
} from '@/api/drill_compete';
export default {
    name: 'ReportSubmit',
    props: ['taskReportListData', 'drillDetail', 'isUpdate','zhSubmitTargetId','zhSubmitTeamId'],
    components: {},
    data() {
        return {
            targetId: this.zhSubmitTargetId || '',
            party: [],
            cascaderData: [],
            isSubmitting: false, //正在保存
            uploadHeader: {
                Authorization: cookieUse.getCookie('desig-token'),
                Accept: '*/*',
            },
            showTip: false,
            showTipInfo: '',
            attack: '',
            attackList: [],
            submitModal: {
                show: false,
                loading: true,
                title: '提交报告',
            },
            tipModal: {
                show: false,
                submitSuccess: true,
                content: '',
            },
            adminTeamId: '',
            targetList: [],
        };
    },
    computed: {
        taskReportListDatas() {
            return this.taskReportListData;
        },
        isTargetAdmin() {
            if (this.party.length) {
                let teamId = this.party[0];
                return teamId === this.adminTeamId;
            } else {
                return false;
            }
        },
        dataInfo() {
            if (!this.party.length) {
                return;
            }
            let teamId = this.party[0],
                teamName;
            let obj = this.cascaderData.find((item) => item.value === teamId) || {};
            teamName = obj.label;
            let params = {
                teamId,
                teamName,
                creator: this.party[1],
                creatorName: obj.children.find((user) => user.value === this.party[1]).label,
            };
            if (this.drillDetail.type !== 7) {
                params.taskId = this.taskReportListData[0].id;
                params.taskName = this.taskReportListData[0].name;
            }
            return params;
        },
        uploadAction() {
            return `/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs`;
        },
    },
    watch: {
        'submitModal.show': function (val) {
            if (!val) {
                this.targetId = this.zhSubmitTargetId || '';
                this.party = [];
                this.targetList = [];
            }
        },
        drillDetail: {
            handler(newValue,oldValue) {
                if(newValue.id != oldValue.id){
                    this.getAttackTypes();
                }
            },
            deep: true,
        },
        isTargetAdmin() {
            if (this.drillDetail.type == 7) {
                return;
            }
            this.$nextTick(() => {
                this.getAttackTypes();
            });
        },
        party() {
            this.$nextTick(() => {
                this.getTargetList();
            });
        },
    },
    created() {
        this._drillDetail = { ...this.drillDetail };
        if(this._drillDetail.id){
            this.getAttackTypes();
        }
        this.getaccessgrouplist();
    },
    methods: {
        getTargetList() {
            if (!this.party.length && this.drillDetail.type !== 7) {
                this.targetList = [];
                return;
            }
            let myPromise;
            if (this.drillDetail.type === 7) {
                //综合演练
                myPromise = queryTargetAllot({
                    pageIndex: 1,
                    pageSize: 2147483647,
                    sceneId: this.$route.query.id,
                    projectId: this.$route.query.prjid,
                    teamId: this.zhSubmitTeamId || this.party[0]
                });
            } else {
                if (this.isTargetAdmin) {
                    myPromise = getPneDefenseTarget({
                        pageIndex: 1,
                        pageSize: 2147483647,
                        // available: true,
                        userId: this.party[1],
                        testId: this.$route.query.id,
                    });
                } else {
                    myPromise = getPneAttackTarget({
                        sceneId: this.$route.query.id,
                        projectId: this.$route.query.prjid,
                        teamId: this.party[0],
                        pageIndex: 1,
                        pageSize: 2147483647,
                        // available: true
                    });
                }
            }
            myPromise
                .then(({ code, message, data = {} }) => {
                    if (code == 1) {
                        this.targetList = data.items;
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        openModal() {
            this.submitModal.show = true;
        },
        // 获取可选的提交人
        getaccessgrouplist() {
            getaccessgrouplist({
                pageIndex: 1,
                pageSize: 2147483647,
                testId: this.$route.query.id,
            }).then(({ code, message, data = {} }) => {
                if (code === 1) {
                    let list = data.items;
                    if(this.drillDetail.type === 7 && this.zhSubmitTeamId){
                        list = list.filter(item => item.id === this.zhSubmitTeamId)
                    }
                    this.cascaderData = list.map((item) => {
                        if (item.name === '目标方管理员组') {
                            this.adminTeamId = item.id;
                        }
                        return {
                            value: item.id,
                            label: item.name,
                            children: (item.userList || []).map((subItem) => {
                                return {
                                    value: subItem.userId,
                                    label: subItem.userName,
                                };
                            }),
                        };
                    });
                } else {
                    this.$Message.error(message);
                }
            });
        },
        // 获取攻击类型列表
        getAttackTypes() {
            let apiName = queryHWAttackTypes;
            let query = { contrapose: this.isTargetAdmin ? '1' : '2' };
            if (this.drillDetail.type === 7) {
                //综合演练，不区分攻击防守，查询所有
                query = { contrapose: null };
            }
            apiName(this.drillDetail.id, query)
                .then(({ code, message, data = {} }) => {
                    if (code == 1) {
                        this.attackList = data;
                        this.attack = this.attackList[0].id;
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        submitReport(file) {
            if (file.code === 1) {
                this.tipModal.content = '文件上传成功,准备提交报告，请稍后...';
                this.isSubmitting = true;
                let { teamId, teamName, taskId, taskName, creator, creatorName } = this.dataInfo; //pneDetail复制传递
                let target =
                    this.targetList.find(
                        (item) => this.targetId === item.id || this.targetId === item.targetId
                    ) || {};
                let {
                    id: id,
                    targetId: targetId,
                    name: targetName,
                    company: targetCompany,
                    publicTarget: publicTarget,
                    category
                } = target;
                let apiName = submitFile;
                if (this.drillDetail.type == 7) {
                    apiName = designerSubmitReport;
                }
                let data = {};
                if (this.isUpdate) {
                    apiName = updateFile;
                    data = {
                        id: file.info.id,
                        name: file.info.originalName,
                        path: file.data,
                    };
                } else {
                    let { projectId, projectName, id: testId, name: testName } = this.drillDetail;
                    if (this.drillDetail.type === 7) {
                        // let rule = this.attackList.find(attack => attack.id === this.attack);
                        data = {
                            approvalInfo: '',
                            approvalTime: '',
                            attackLevel: '',
                            attackType: this.attack,
                            fileId: file.info.id,
                            fileName: file.info.originalName,
                            level: '',
                            questionId: target.id,
                            questionName: target.targetName,
                            sceneId: testId,
                            score: 0,
                            teamId: teamId,
                            teamName: teamName,
                            userId: creator,
                            userName: creatorName,
                        };
                    } else {
                        data = {
                            reportName: file.info.originalName,
                            testId: testId,
                            testName: testName,
                            groupId: teamId,
                            groupName: teamName,
                            taskId: taskId,
                            taskName: taskName,
                            category,
                            target: this.isTargetAdmin ? id : targetId,
                            targetName: targetName,
                            company: targetCompany,
                            projectId: projectId,
                            projectName: projectName,
                            type: this.isTargetAdmin ? 2 : 1,
                            publicTarget: !!publicTarget,
                            files: [
                                {
                                    id: file.info.id,
                                    name: file.info.originalName,
                                    path: file.data,
                                },
                            ],
                            startTime: '',
                            endTime: '',
                            creator: creator,
                        };
                        // 目标管理员-防守方
                        if (this.isTargetAdmin) {
                            data.defenseType = this.attack;
                        } else {
                            //攻击方
                            data.attackType = this.attack;
                        }
                    }
                }
                // 修改接口需要额外传递id，添加接口id传不传都不影响，所以一起传递了
                apiName(data, id).then((res) => {
                    this.isSubmitting = false;
                    this.tipModal.show = true;
                    if (res.code == 1) {
                        this.tipModal.content = '提交报告成功';
                        this.tipModal.submitSuccess = true;
                        this.$emit('upload-success');
                    } else {
                        this.tipModal.submitSuccess = false;
                        this.tipModal.content = res.message;
                    }
                    setTimeout(() => {
                        this.tipModal.show = false;
                        this.tipModal.content = '';
                        this.submitModal.show = false;
                    }, 2000);
                });
            } else {
                this.tipModal.submitSuccess = false;
                this.isSubmitting = false;
                this.tipModal.show = true;
                this.tipModal.content = file.message;
                setTimeout(() => {
                    this.tipModal.show = false;
                    this.tipModal.content = '';
                }, 2000);
            }
        },
        beforeUpload(file) {
            // const fileSize = file.size / 1024 / 1024 > this.$store.state.common.fileMax;
            // if(fileSize){
            // this.$Message.error({
            //     content: `文件大小不能大于${this.$store.state.common.fileMax}M`,
            //     duration: 2
            // });
            // return false;
            // }
            this.showTip = false;
            let name = file.name.split('.')[0];
            // let reg = /^[0-9a-zA-Z_\u4e00-\u9fa5]*$/;
            // ？‘’“”
            let reg = /[\\/:*?"<>|]/gi;
            if (reg.test(name)) {
                this.showTip = true;
                // this.showTipInfo = `文件名只能包含数字，字母，汉字和下划线`;
                this.showTipInfo = '文件名不能包含下列任意英文字符 \\ / : * ? " < > |';
                return false;
            }
            if (name.length > 50) {
                this.showTip = true;
                this.showTipInfo = `文件名的长度不能超过50个字符`;
                return false;
            }
        },
        handleFormatError(sss) {
            this.$Message.warning('文件格式错误，请上传word或pdf文档');
        },
        fileHasExceed(file, fileList) {
            this.showTip = true;
            this.showTipInfo = `请上传10M以内的文档`;
        },
        handleUploadProgress(event) {
            this.tipModal.show = true;
            this.tipModal.content = `文件已上传${parseInt(event.percent)}%，请稍后...`;
        },
    },
};
</script>

<style>
.tipModel .ivu-modal-footer {
    border-top: none;
}
.tipModel .ivu-modal-footer > button:first-child,
.tipModel .ivu-modal-close {
    display: none !important;
}
.report .ivu-upload-drag {
    text-align: left;
    border: none;
}
.report .ivu-alert-warning {
    border: none;
    background-color: transparent;
}
.report .ivu-alert {
    margin-bottom: 0;
}
.report .ivu-upload-drag:hover {
    border: none;
}
.report .ivu-tooltip-rel {
    width: 100%;
    text-overflow: ellipsis;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    word-break: normal;
    vertical-align: middle;
}
.tipModel .ivu-modal-confirm-head-icon-warning .ivu-icon-ios-checkmark-circle:before {
    content: '\F108';
}
</style>
<style scoped>
.search-group {
    margin-bottom: -8px;
}
.search-group /deep/ .search-item {
    margin-bottom: 8px;
}
</style>
